package auth

import (
	"encoding/base64"
	binaryUtils "encoding/binary"
	"strings"
	"time"

	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/setting"
	"code.gitea.io/gitea/services/context"
	"github.com/google/uuid"
)

// Define a Wechat Error type message
type WechatError struct {
	message string
}

// Implement the Error() method for the `WechatError` type
func (e *WechatError) Error() string {
	return e.message
}

/**
 * 生成微信临时二维码
 *
 * @param ctx 页面会话上下文环境
 * @return string 生成的微信二维码的 ticket
 * @return error 如果生成二维码过程中出现错误，则返回相应的错误信息
 */
func GenerateWechatQr(ctx *context.Context) (wechatQrTicket string, errorGenerateQr error) {

	if setting.Wechat.OfficialAccount.PowerWechat == nil {
		log.Warn("PowerWechat工具类配置错误, 不会生成公众号带参数二维码")
		return "", &WechatError{message: "ERROR: PowerWechat 配置错误 (PowerWechat app instance has not yet been initialized!)"}
	}

	// 生成随机 sceneStr 场景值
	//  sceneStr生成规则：UUIDv4后边拼接 当前UnixNano时间戳转为byte数组后的Base64
	//  e.g, sceneStr == "1c78e8d914fb4307a3588ac0f6bc092a@yPXAm+ve5hc="
	bytesArrayUnit64 := make([]byte, 8)
	binaryUtils.LittleEndian.PutUint64(bytesArrayUnit64, uint64(time.Now().UnixNano()))
	currentTimestampNanoBase64 := base64.StdEncoding.EncodeToString(bytesArrayUnit64)
	sceneStr := strings.ReplaceAll(uuid.New().String(), "-", "") + "@" + currentTimestampNanoBase64

	qrExpireSeconds := setting.Wechat.OfficialAccount.TempQrExpireSeconds
	qrData, err := setting.Wechat.OfficialAccount.PowerWechat.QRCode.Temporary(ctx, sceneStr, qrExpireSeconds)
	if err == nil {
		wechatQrTicket = qrData.Ticket
		ctx.Data["wechatQrTicket"] = wechatQrTicket
		ctx.Data["wechatQrCodeUrl"] = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + wechatQrTicket
		ctx.Data["wechatQrExpireSeconds"] = qrData.ExpireSeconds
	} else {
		log.Warn(" [!] 无法生成微信公众号带参数临时二维码: %s", err.Error())
	}
	return wechatQrTicket, err
}
